package com.orange.off.cloud.cloudoff.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.activity.IntermediaryActivity;
import com.orange.off.cloud.cloudoff.adapters.MySpinnerAdapter;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.CertificationEvent;
import com.orange.off.cloud.cloudoff.model.NoAuthenticationRealEstateListBean;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.GsonUtils;
import com.orange.off.cloud.cloudoff.utils.ProgressDlgUtil;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;
import com.orange.off.cloud.cloudoff.views.SpinerPopWindow;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 身份认证界面，通用
 *
 * @author smile
 */
public class CommAuthenticationFragment extends Fragment {


    @Bind(R.id.rt_commAuthenticationBack)
    RelativeLayout imgCommAuthenticationBack;
    @Bind(R.id.sp_type)
    Spinner spType;

    @Bind(R.id.linearLayout_RealEstateBroker)//经纪公司
            LinearLayout linearLayoutRealEstateBroker;
    @Bind(R.id.edt_brokerCode)//经纪公司识别码
            EditText edtBrokerCode;
    @Bind(R.id.tv_ApplyEstateNamebroker)//楼盘名
            TextView tvApplyEstateNamebroker;

    @Bind(R.id.linearLayout_ElectricityCustomers)//电商拓客
            LinearLayout linearLayoutElectricityCustomers;
    @Bind(R.id.tv_ApplyEstateCode)//拓客识别码
            EditText tvApplyEstateCode;
    @Bind(R.id.tv_ApplyEstateName)//楼盘名
            TextView tvApplyEstateName;

    @Bind(R.id.linearLayout_ProjectOwner)//项目业主
            LinearLayout linearLayoutProjectOwner;
    @Bind(R.id.tv_buyRealEstate)//楼盘名
            TextView tvBuyRealEstate;
    @Bind(R.id.edt_roomNo)//所购房号
            EditText edtRoomNo;

    @Bind(R.id.edt_propertyConsultantName)//置业顾问名字
            EditText edtPropertyConsultantName;
    @Bind(R.id.authentication_account_button)
    LinearLayout authenticationAccountButton;
    @Bind(R.id.authentication_submit_button)
    Button authenticationSubmitButton;
    @Bind(R.id.authentication_account_check_button)
    Button checkButton;
    @Bind(R.id.authentication_account_text)
    TextView authenticationAccountText;
    @Bind(R.id.authentication_account_linear)
    LinearLayout authenticationAccountLinear;


    private String[] spinnerArray = {"经纪公司", "电商拓客", "项目业主"};
    //    private String[] spinnerArray = {"内部员工", "经纪公司", "电商拓客", "项目业主"};
    String typeName = "";//认证类型
    String project_id = "";//项目id
    String availability = "";//所购房源(楼号)
    String consultant = "";//置业顾问
    String identifier = "";//识别码
    int popType = 1;
    String identity = "";//指定跳转身份类别1：有项目id及名称。2：个人中心身份认证没有id及项目名称


    Boolean isCheck = true;
    private SpinerPopWindow<NoAuthenticationRealEstateListBean> mSpinerPopWindow;


    private List<NoAuthenticationRealEstateListBean> noAuthenticationLists = new ArrayList<NoAuthenticationRealEstateListBean>();

    public static CommAuthenticationFragment newInstance(String project_name, String id, String identity) {
        CommAuthenticationFragment fragment = new CommAuthenticationFragment();
        Bundle args = new Bundle();
        args.putString("project_name", project_name);
        args.putString("id", id);
        args.putString("identity", identity);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        if ("2".equals(identity)) {
            getNoAuthenticationListData();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.commauthentication_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    private void initViews() {
        identity = getArguments().getString("identity");
        String project_name = getArguments().getString("project_name");
        project_id = getArguments().getString("id");
        tvApplyEstateNamebroker.setText(project_name);
        tvApplyEstateName.setText(project_name);
        tvBuyRealEstate.setText(project_name);
        mSpinerPopWindow = new SpinerPopWindow<NoAuthenticationRealEstateListBean>(getActivity(), noAuthenticationLists, PopItemClickListener);
        mSpinerPopWindow.setOnDismissListener(dismissListener);
        MySpinnerAdapter adapter = new MySpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item, spinnerArray);
        spType.setAdapter(adapter);

        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                typeName = spType.getSelectedItem().toString();
                if ("经纪公司".endsWith(typeName)) {
                    //显示经纪公司，隐藏内部员工、电商拓客、项目业主：
                    linearLayoutRealEstateBroker.setVisibility(View.VISIBLE);
                    linearLayoutElectricityCustomers.setVisibility(View.GONE);
                    linearLayoutProjectOwner.setVisibility(View.GONE);
                    availability = "";//所购房源(楼号)
                    consultant = "";//置业顾问
                } else if ("电商拓客".endsWith(typeName)) {
                    //显示电商拓客，隐藏内部员工、经纪公司、项目业主：
                    linearLayoutElectricityCustomers.setVisibility(View.VISIBLE);
                    linearLayoutRealEstateBroker.setVisibility(View.GONE);
                    linearLayoutProjectOwner.setVisibility(View.GONE);
                    availability = "";//所购房源(楼号)
                    consultant = "";//置业顾问
                } else if ("项目业主".endsWith(typeName)) {
                    //显示项目业主，隐藏内部员工、电商拓客、经纪公司：
                    linearLayoutProjectOwner.setVisibility(View.VISIBLE);
                    linearLayoutElectricityCustomers.setVisibility(View.GONE);
                    linearLayoutRealEstateBroker.setVisibility(View.GONE);
                    identifier = "";//识别码
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    /**
     * 监听popupwindow取消
     */
    private PopupWindow.OnDismissListener dismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            //            setTextImage(R.drawable.icon_down);
        }
    };

    /**
     * popupwindow显示的ListView的item点击事件
     */
    private AdapterView.OnItemClickListener PopItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mSpinerPopWindow.dismiss();
            if (noAuthenticationLists.size() > 0) {
                project_id = noAuthenticationLists.get(position).id;
                switch (popType) {
                    case 1://经纪公司
                        tvApplyEstateNamebroker.setText(noAuthenticationLists.get(position).name);
                        break;
                    case 2://电商拓客
                        tvApplyEstateName.setText(noAuthenticationLists.get(position).name);
                        break;
                    case 3://项目业主
                        tvBuyRealEstate.setText(noAuthenticationLists.get(position).name);
                        break;
                }
            } else {
                project_id = "";
            }


        }
    };

    @OnClick({R.id.rt_commAuthenticationBack, R.id.authentication_account_button, R.id.authentication_submit_button
            , R.id.tv_ApplyEstateNamebroker, R.id.tv_ApplyEstateName, R.id.tv_buyRealEstate, R.id.authentication_account_linear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rt_commAuthenticationBack:
                //返回：
                getActivity().finish();
                break;
            case R.id.tv_ApplyEstateNamebroker://经纪公司
                if ("2".equals(identity)) {
                    //未传过来楼盘名字及id触发下拉选择楼盘操作
                    mSpinerPopWindow.setWidth(view.getWidth());
                    mSpinerPopWindow.showAsDropDown(view);
                    popType = 1;
                }

                break;
            case R.id.tv_ApplyEstateName://拓客公司
                if ("2".equals(identity)) {
                    //未传过来楼盘名字及id触发下拉选择楼盘操作
                    mSpinerPopWindow.setWidth(view.getWidth());
                    mSpinerPopWindow.showAsDropDown(view);
                    popType = 2;
                }
                break;
            case R.id.tv_buyRealEstate://项目业主
                if ("2".equals(identity)) {
                    //未传过来楼盘名字及id触发下拉选择楼盘操作
                    mSpinerPopWindow.setWidth(view.getWidth());
                    mSpinerPopWindow.showAsDropDown(view);
                    popType = 3;
                }
                break;
            case R.id.authentication_account_button:
                //认证须知按钮：
                AccountButton();
                break;
            case R.id.authentication_account_linear:
                //认证须知跳转：
                Intent intent = new Intent(getActivity(), IntermediaryActivity.class);
                intent.putExtra("type", IntermediaryActivity.COMM_AUTHENTICATION_NOTICE_FRAGMENT);
                startActivity(intent);
                break;
            case R.id.authentication_submit_button:
                //申请认证：
                if ("经纪公司".endsWith(typeName)) {
                    String brokerCode = edtBrokerCode.getText().toString().trim();
                    if (TextUtils.isEmpty(brokerCode)) {
                        ToastUtils.show(getActivity(), "请输入经纪人识别码");
                        return;
                    }
                    availability = "";//所购房源(楼号)
                    consultant = "";//置业顾问
                    Submit(typeName, brokerCode, availability, consultant);
                } else if ("电商拓客".endsWith(typeName)) {
                    String applyEstateCode = tvApplyEstateCode.getText().toString().trim();
                    if (TextUtils.isEmpty(applyEstateCode)) {
                        ToastUtils.show(getActivity(), "请输入拓客识别码");
                        return;
                    }
                    availability = "";//所购房源(楼号)
                    consultant = "";//置业顾问
                    Submit(typeName, applyEstateCode, availability, consultant);
                } else if ("项目业主".endsWith(typeName)) {
                    identifier = "";//识别码
                    Submit("项目业主", identifier, edtRoomNo.getText().toString().trim(), edtPropertyConsultantName.getText().toString().trim());

                }
                break;
        }
    }

    /**
     * 申请认证提交
     * code：经纪公司，电商拓客识别码
     * room:所购房源(房间号)
     * guwen:置业顾问姓名
     */
    void Submit(String type, String code, String room, String guwen) {
        if (TextUtils.isEmpty(project_id)) {
            ToastUtils.show(getActivity(), "认证项目不能为空");
            return;
        }
        ProgressDlgUtil.showProgressDlg("认证中,请稍后...", getActivity());
        authenticationSubmitButton.setEnabled(false);
        RequestParams params = new RequestParams();
        params.addFormDataPart("xid", project_id);
        params.addFormDataPart("aid", MyApplication.aid);
        params.addFormDataPart("type", type);
        params.addFormDataPart("code", code);
        params.addFormDataPart("room", room);
        params.addFormDataPart("guwen", guwen);
        Log.d(MyApplication.DEBUG, "身份认证xid-->" + project_id + "--aid-->" + MyApplication.aid + "--type-->" + typeName + "--code--》" + code
                + "--room-->" + room + "--guwen-->" + guwen);
        HttpRequest.post(AppUrls.Certification, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                ProgressDlgUtil.stopProgressDlg();
                authenticationSubmitButton.setEnabled(true);
                Log.d(MyApplication.DEBUG, "身份认证--success-》" + uploadResponse.toString());

                if (uploadResponse.getSuccess()) {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                    EventBus.getDefault().post(new CertificationEvent(true));
                    getActivity().finish();

                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                ProgressDlgUtil.stopProgressDlg();
                authenticationSubmitButton.setEnabled(true);
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    /**
     * 获取未认证楼盘列表
     */
    void getNoAuthenticationListData() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("aid", MyApplication.aid);
        params.addFormDataPart("type", "renzheng");
        Log.d(MyApplication.DEBUG, "未认证楼盘_url---》" + AppUrls.Reported + "--type-->renzheng");
        HttpRequest.post(AppUrls.Reported, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                Log.d(MyApplication.DEBUG, "未认证楼盘--success-》" + uploadResponse.toString());
                if (uploadResponse.getSuccess()) {
                    try {
                        Type type = new TypeToken<ArrayList<NoAuthenticationRealEstateListBean>>() {
                        }.getType();
                        List<NoAuthenticationRealEstateListBean> list = GsonUtils.getList(uploadResponse.getData(), type);
                        if (list.size() <= 0) {
                            ToastUtils.show(getActivity(), "暂无数据");
                        }
                        noAuthenticationLists = list;
                        mSpinerPopWindow.setData(noAuthenticationLists);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    private void AccountButton() {
        if (isCheck) {
            isCheck = false;
            checkButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_check_false));
            authenticationSubmitButton.setBackgroundColor(getResources().getColor(R.color.grey));
            authenticationSubmitButton.setEnabled(false);
        } else {
            isCheck = true;
            checkButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_check_true));
            authenticationSubmitButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_press_selector));
            authenticationSubmitButton.setEnabled(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            getActivity().finish();
            return true;
        }
        return false;
    }


}
